var nbcgdContent = {
    initComponent: function () {
        //发货公司
        $("#cgd_fhgs_id").qyjgcombobox();
        //到货仓库
        $("#cgd_dhck_id").ckcombobox();
        //承运单位
        $("#cgd_ysdw_id").wlscombobox();
        //税率
        $('#cgd_sl').slsjzdcombobox("sl");

        $("#cgd_gys_id").combotree({
            loadFilter: function (rows) {
                return convert(rows);
            }
        });
    },
    initBtn: function () {
        //新增采购单明细
        $("#cgd_content_mx_add").click(function () {
            searchcodewindow(cgdmx_searchWindowOKbtnHandler);
        });
        //删除采购单明细
        $("#cgd_content_mx_del").click(function () {
            var rows = $("#cgd_mx").edatagrid('getChecked');
            if (rows) {
                $.messager.confirm('提示', '是否确定删除送货单明细?', function (r) {
                    if (r) {
                        $.each(rows, function (i, val) {
                            var index = $("#cgd_mx").edatagrid('getRowIndex', val);
                            $("#cgd_mx").edatagrid('deleteRow', index);
                        });
                        countSumCgdmx();
                    }
                });
            }
            $("#cgd_mx").edatagrid('resize');
        });
        //新增费用明细
        $("#cgd_content_glfy_add").click(function () {
            var data = {
                'sydw.id': null,
                'fylb.id': null,
                'jfsl': 0,
                'dj': 0,
                'je': 0,
                'bz': null
            };
            $("#cgd_fy").edatagrid('appendRow', data);
        });
        //删除合同费用
        $("#cgd_content_glfy_del").click(function () {
            var rows = $("#cgd_fy").edatagrid('getChecked');
            if (rows) {
                $.messager.confirm('提示', '是否确定删除销售费用?', function (r) {
                    if (r) {
                        $.each(rows, function (i, val) {
                            var index = $("#cgd_fy").edatagrid('getRowIndex', val);
                            $("#cgd_fy").edatagrid('deleteRow', index);
                        });
                    }
                });
            }
            $("#cgd_fy").edatagrid('resize');
        });
    },
    //显示合同内容
    showCgdInfo: function () {
        $("#table_nbcgdContent").show();
    },
    isNew: function () {
        return $("[name='cgd.id']").val() == "";
    },
    fillData: function () {
        fillHtmxByCgd();
        fillFyByCgd();
    }
};

$(function () {
    nbcgdContent.initComponent();
    nbcgdContent.initBtn();
    nbcgdContent.fillData();
    nbcgdContent.showCgdInfo();
    nbcgdContent.showCgdInfo();
})

function fillHtmxByCgd() {
    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
            fillHtmx($.webPath() + '/cggl/nbcgd/nbcgd_cgmx?cgd.id=' + $("[name='cgd.id']").val() || '', cddata, data);
        })
    });
}

function fillFyByCgd() {
    $.post($.webPath() + '/organ/wls/wlsInuseList', function (jgdata) {
        $.post($.webPath() + '/cwgl/kmys/cyfyys/fylbcombobox', {'gsId': $("[name='cgd.cggs.id']").val()}, function (data) {
            fillFy($.webPath() + '/cggl/nbcgd/nbcgd_cgfy?cgd.id=' + $("[name='cgd.id']").val() || '', jgdata, data);
        })
    })
}

function fillHtmx(href, cdOptions, fsOptions) {
    $("#cgd_mx").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        toolbar: "#nbcgd_cgdmx_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'wzgg.code', title: '物资编码', width: 30},
                {field: 'wzgg.name', title: '物资名称', width: 20},
                {field: 'wzgg.ggxh', title: '规格型号', width: 20},
                {field: 'wzgg.dw', title: '单位', width: 10},
                {field: 'cd.id', editor: {type: 'combobox', options: {
                    data: cdOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '150'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < cdOptions.length; i++) {
                        if (cdOptions[i].id == value) return cdOptions[i].z;
                    }
                    return value;
                }, title: '产地', width: 30},
                {field: 'jzfs.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '55'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title: '记重方式', width: 25},
                {field: 'js', editor: {type: 'numberbox', options: {min: 0, precision: 0}}, title: '件数',
                    formatter:function(value){
                        var sl = formatSl(value,",");
                        return sl;
                    } ,width: 40},
                {field: 'sbsl', editor: {type: 'numberbox', options: {min: 0, precision: 4}}, title: '数量',
                    formatter:function(value){
                        var sl = formatSl(value,",");
                        return sl;
                    } ,width: 50},
                {field: 'hsj', editor: {type: 'numberbox', options: {min: 0, precision: 4,groupSeparator:','}}, title: '含税单价(元)',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    } ,width: 50},
                {field: 'bhsj', editor: {type: 'numberbox', options: {min: 0, precision: 4,groupSeparator:','}}, title: '不含税单价(元)',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    } ,width: 50}
            ]
        ],
        onSelect: function (rowIndex) {
            //获取每个单元格
            $("#cgd_mx").edatagrid('editRow', rowIndex);
            var editors = $("#cgd_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var hsjEditor = editors[4];
            var bhsjEditor = editors[5];
            hsjEditor.target.unbind("change").bind('change', function () {
                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());
                var bhsj = tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#cgd_sl").combobox('getValue'));
                if (!$(bhsjEditor.target).numberbox('getValue'))
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                else if (Math.abs($(bhsjEditor.target).numberbox('getValue') - bhsj) >= 0.01) {
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                }
                countSumCgdmx();
            });
            bhsjEditor.target.unbind("change").bind('change', function () {
                $(bhsjEditor.target).numberbox('setValue', $(bhsjEditor.target).val());
                var hsj = tax.getIncludingTaxPrice($(bhsjEditor.target).numberbox('getValue'), $("#cgd_sl").combobox('getValue'));
                if (!$(hsjEditor.target).numberbox('getValue'))
                    $(hsjEditor.target).numberbox('setValue', hsj);
                else if (Math.abs($(hsjEditor.target).numberbox('getValue') - hsj) > 0.01) {
                    $(hsjEditor.target).numberbox('setValue', hsj);
                }
                countSumCgdmx();
            });
        },
        onLoadSuccess: function () {
            countSumCgdmx();
        }
    })
}

//查询物资代码确定按钮回调函数
function cgdmx_searchWindowOKbtnHandler(datas) {
    $.each(datas, function () {
        $("#cgd_mx").edatagrid('appendRow', {
            'kh.id': null,
            'wzgg.id': this.id,
            'wzgg.code': this.code,
            'wzgg.name': this.name,
            'wzgg.ggxh': this.ggxh,
            'wzgg.dw': this.dw,
            'cd.id': this.cd_id,
            'kkdsl': 0,
            'sbsl': 0,
            'jzfs.id': null,
            'bhsj': 0,
            'hsj': 0,
            'bz': ''
        });
    });
}

function fillFy(href, jgOptions, fsOptions) {
    $("#cgd_fy").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        toolbar: "#nbcgd_cgdfy_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'sydw.id', editor: {type: 'combobox', options: {
                    data: jgOptions,
                    valueField: 'id',
                    textField: 'qc',
                    multiple: false,
                    panelHeight: '200'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < jgOptions.length; i++) {
                        if (jgOptions[i].id == value) return jgOptions[i].qc;
                    }
                    return value;
                }, title: '收益单位', width: 40},
                {field: 'fylb.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'fykmjc',
                    multiple: false,
                    panelHeight: '110'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].fykmjc;
                    }
                    return value;
                }, title: '费用类别', width: 17},
                {field: 'jfsl', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '计费数量',
                    formatter:function(value){
                        var sl = formatSl(value,",");
                        return sl;
                    } ,width: 40},
                {field: 'dj', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '单价',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    } ,width: 50},
                {field: 'je', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 2}}, title: '总金额',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    } ,width: 50},
                {field: 'bz', editor: {type: 'text'}, title: '备注', width: 30}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#cgd_fy").edatagrid('editRow', rowIndex);
            var editors = $("#cgd_fy").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var jfslEditor = editors[2];
            var djEditor = editors[3];
            var jeEditor = editors[4];

            jfslEditor.target.unbind("blur").bind('blur', function () {
                $(jfslEditor.target).numberbox('setValue', $(jfslEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });
            djEditor.target.unbind("blur").bind('blur', function () {
                $(djEditor.target).numberbox('setValue', $(djEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });
        }
    })
}

$('#nbcgdForm').tabs({

    border: false,
    onSelect: function (title) {

        if (title == "送货单打印") {
            //判断合同有没有保存
            if (null == $("[name='cgd.id']").val() || $("[name='cgd.id']").val() == '') {
                $('#nbcgdForm').tabs('select', "送货明细");
                $.messager.alert('提示', '先保存送货单明细，才能编辑送货单打印文本', 'info');
            } else {
                $.ajax({
                    type: "POST",
                    url: $.webPath() + '/cggl/nbcgd/cgdDetail?cgdId=' + $("input[name='cgd.id']").val(),
                    dataType: "html",
                    beforeSend: function () {
                        $.messager.progress();
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        $('#cgddy_cgd_id').html(data);
                        if (data.statusCode == 300) {
                        }
                        if (data.statusCode == 200) {
                        }
                    }
                });
            }

        }
    }
});

//  检查插件
function cgd_checkIsInstall() {
    try {
        var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
        if ((LODOP != null) && (typeof(LODOP.VERSION) != "undefined"))
            alert("本机已成功安装过Lodop控件!\n  版本号:" + LODOP.VERSION);
    } catch (err) {
        alert("Error:本机未安装或需要升级!");
    }
};

function createCgdHtml(){
    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    LODOP.SET_PRINT_STYLEA(0,"NotOnlyHighPrecision",true);
    LODOP.PRINT_INIT("预览送货单");
    var strBodyStyle = "<style  type=\"text/css\">" +
        ".input-tian{border-top-style:none;border-left-style:none;border-right-style:none;border-bottom-style: 1px solid #57626a;height:22px;line-height:22px;width:100%;color:#485f71;font-weight: bold;background: #F6F9FF;}," +
        " select{display:none}," +
        ".tb{width:auto;border-collapse:collapse;border-spacing:0;color:#485f71;}," +
        ".tb th{padding:2px 2px 2px 12px;font-weight:normal;text-align: right;}," +
        ".tb td{padding:2px;},.tb caption{ font-size:24px;height:30px;line-height:30px;}" +
        ".intb{width: 100%;},.intb,.intb th,.intb td{border:1px #57626a solid;}" +
        "</style>";
    var strFormHtml = strBodyStyle + "<body>" + document.getElementById("cgddy_print_id").innerHTML + document.getElementById("cgddy_cgd_id").innerHTML + document.getElementById("cgddy_print_end").innerHTML + "</body>";
    var cgd_cgdh = $("#cgd_cgdh").val();
    var cgd_ewmtime = $("#cgd_ewmtime").val();

    LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", "Auto-Width");
    LODOP.ADD_PRINT_HTM(40, 50, 700, 600, strFormHtml);
    LODOP.ADD_PRINT_BARCODE(28,650,100,100,'QRCode',cgd_cgdh+" "+cgd_ewmtime);
    LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",3);
    return LODOP;
}

// 打印预览.
function cgd_printPreview() {
    var LODOP=createCgdHtml();
    LODOP.PREVIEW();
}

// 打印
function cgd_print() {
    var LODOP=createCgdHtml();
    LODOP.PRINT();
}

//采购单明细合计
function countSumCgdmx() {
    var sumSbsl = 0;
    var sumHsj = 0;
    var sumBhsj = 0;
    var data = $("#cgd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]["sbsl"]);
        var hsj = parseFloat(data.rows[i]["hsj"]);
        var bhsj = parseFloat(data.rows[i]["bhsj"]);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        bhsj = isNaN(bhsj) ? 0 : bhsj;
        sumSbsl += sbsl;
        sumHsj += hsj;
        sumBhsj += bhsj;
    }
    addFooter(sumSbsl,sumHsj,sumBhsj);
}

function addFooter(sumSbsl,sumHsj,sumBhsj) {
    var footer = null;
    footer = [
        {"wzgg.code": "合计", "sbsl": formatMoneyFourWei(sumSbsl),"hsj":formatMoneyFourWei(sumHsj),"bhsj":formatMoneyFourWei(sumBhsj)}
    ];
    if (footer != null)
        $("#cgd_mx").edatagrid('reloadFooter', footer);
}
